import {Component, OnInit, OnDestroy} from '@angular/core';
import  {ChatService} from  './service/chat.service';
import {UserClass} from "./class/user-class";
import {MessageClass} from "./class/message-class";
import {CMD} from './cid'
import  {LSService} from  './service/localStorage.service';
import  {UserService} from  './service/user.service';

@Component({// 定义组件相关的metadata信息
    selector: '.main',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ChatService]
})
export class AppComponent implements OnInit, OnDestroy {
    constructor(private chatService: ChatService,
                private localStorageService: LSService,
                private userService: UserService) {
    }

    connection;
    loginInfo: UserClass = <UserClass>{};

    //对应发送消息的输入框，待扩展
    say = {
        words: "",
        color: 0xFF0000
    };

    users = [];
    messages = [];
    receiver: UserClass = <UserClass>{};

    //words: string;
    privateMessages = {};
    publicMessages = [];


    //登录请求
    login(mLoginInfo) {
        if (!mLoginInfo.userName.trim()) return;

        this.chatService.sendLoginMessage({userName: mLoginInfo.userName, pwd: mLoginInfo.password});
    }

    postMessage() {
        if (!this.say.words) return;

        //const timeStamp = new Date().toLocaleTimeString();
        const timeStamp = new Date().toLocaleString();
        console.log('timeStamp====' + timeStamp);
        let msg: MessageClass = <MessageClass>{} ;

        console.log('msg.type ===' + msg.type);

        msg.content = this.say.words;
        msg.type = "normal";
        msg.color = this.loginInfo.color;
        //msg.friend=this.receiver.userName;
        msg.fromID = this.loginInfo.userID;
        msg.from = this.loginInfo.userName,
        msg.toID = this.receiver.userID;
        msg.to = this.receiver.userName;
        msg.timeStamp = timeStamp;

        console.dir(msg);
        console.debug('接收者====');
        console.log(this.receiver);

        //查询 messages 对象使用的 userName,不使用ID
        //ID 自动增长的,不适合用于查询,待全部改成 userName 索引
        var rec = this.receiver.userName;
        console.log(rec);

        if (rec != 'all') {
            //私信 ： 如果没有给他发过,新建立一个 privateMessages 数组
            if (!this.privateMessages[rec]) {
                this.privateMessages[rec] = [];
            }
            //如果有了,追加本次信息到该朋友
            this.privateMessages[rec].push(msg);

            this.setPrivateMessagesToLS(msg.from, msg.to, this.privateMessages[rec]);
        }
        else {
            //群聊
            this.publicMessages.push(msg);
            this.messages = this.publicMessages;

            //console.dir(this.messages);
            this.setPublicMessagesToLS(this.publicMessages);
        }

        //排除给自己发的情况:已经在html 做了不显示处理，不会出现自己发给自己，但是，逻辑上还是保留
        if (rec !== this.loginInfo.nickname) {
            //自己发给自己只在本地显示，不要发送到服务端，当然如果系统要求，可以放开
            this.chatService.sendChatMessage(msg);
        }

        this.say.words = "";
    };


    ngOnInit() {
        this.connection = this.chatService.getMessages().subscribe(data => {
            if (data) {
                let res: any;
                res = data;

                console.log(" subscribe res.CID = " + res.CID);
                console.debug(res);

                switch (res.CID) {
                    case CMD.userAddingResult.CID:
                        if (res.result) {
                            this.loginInfo.hasLogined = true;
                            this.loginInfo.disconnect = false;
                            this.loginInfo.tips = res.tips;
                            this.loginInfo.userName = res.data.userName;
                            this.loginInfo.color = res.data.color;
                            this.loginInfo.pic = res.data.pic;
                            this.doing_userAddingResult(res.data);
                        }
                        else {
                            console.log(res.tips);
                            this.loginInfo.hasLogined = false;
                            this.loginInfo.disconnect = false;
                            this.loginInfo.tips = res.tips;
                        }
                        break;
                    case CMD.allUser.CID:
                        this.doing_allUser(res.data);
                        break;
                    case CMD.userAdded.CID:
                        this.doing_userAdded(res.data);
                        break;
                    case CMD.messageAdded.CID:
                        this.doing_messageAdded(res.data);
                        break;
                    case CMD.userRemoved.CID:
                        if (res.data)
                            this.doing_userRemoved(res.data);
                        break;
                    default:
                        console.log(' 大概 disconnect 啦！');
                        //error,disconnect..会，先简单判断 disconnect
                        //按照这个内容有没有 close 来判断是不是 disclose transport close
                        this.loginInfo.disconnect = true;

                        break;
                }


            }
            else {
                console.log('没有收到数据包，no data');
                //还有那些是没有数据包？先假设 只有 connect,reconnect 才到这里
                //如果是 reconnect ，重发一次  login
                if (this.loginInfo.disconnect)
                    this.login(this.loginInfo);

            }

        })
    }

    //noinspection JSMethodCanBeStatic
    onMessageClicked(message) {
        //待以后扩展
        console.log('onMessageClicked doing ...');
        console.dir(message);
    }

    ngOnDestroy() {
        this.connection.unsubscribe();
    }

    doing_userAddingResult(res) {
        console.log('用户登陆的结果 33 ---');
        console.log(res);
        //console.log(res.result);

        //userAddingResult 成功之后,首先读取 LS 的历史记录:群聊的
        this.publicMessages = this.getPublicMessagesFromLS();
        this.messages = this.publicMessages;
    }

    doing_allUser(data) {
        console.log('doing_allUSER');
        console.dir(data);
        this.users = data;

        //add by wzh 20170720 同时设定 receiver,初次可以这样，但是后面已经选择过呢？待处理
        this.setReceiver(this.users[0]);
    }

    doing_userAdded(data) {
        console.log('doing_userAdded');
        if (!this.loginInfo.hasLogined) return;

        // 给公共信息加上一条 欢迎
        this.publicMessages.push({content: " 欢迎你！ " + data.nickname + " ", type: "welcome"});
        //测试，
        this.messages = this.publicMessages;
        console.log(this.publicMessages);
        this.users.push(data);

    }

    doing_userRemoved(data) {
        console.log('doing_userRemoved====');
        console.log(data);
        if (!this.loginInfo.hasLogined) return;

        //给公用信息添加一条： bye
        this.publicMessages.push({content: "再见啦！ " + data.nickname + " ", type: "bye"});
        //测试，
        this.messages = this.publicMessages;
        for (var i = 0; i < this.users.length; i++) {
            if (this.users[i].userName == data.userName) {
                //删除该元素
                this.users.splice(i, 1);
                return;
            }
        }
        console.log(this.users);
    }

    doing_messageAdded(data) {
        console.log('doing_messageAdded====');
        console.dir(data);

        if (!this.loginInfo.hasLogined) return;
        //改用 toID 判断,to 空怎么判断不对呢?
        if (data.to != 'all') { //私信
            if (!this.privateMessages[data.from]) {
                this.privateMessages[data.from] = [];
            }

            this.privateMessages[data.from].push(data);

            this.setPrivateMessagesToLS(this.loginInfo.userName, data.from, this.privateMessages[data.from]);
        } else {//群发
            this.publicMessages.push(data);
            this.setPublicMessagesToLS(this.publicMessages);
        }

        var fromUser = this.userService.get(this.users, data.from, data.from);
        var toUser = this.userService.get(this.users, data.to, data.to);
        console.log('data.from ==' + data.from);
        console.log(fromUser);
        console.log('data.to ==' + data.to);
        console.log(toUser);

        if (this.receiver.userName !== data.to) {//与来信方不是正在聊天当中才提示新消息
            if (fromUser.userName != 'all' && toUser.userName != 'all') {
                fromUser.hasNewMessage = true;//私信
            } else {
                toUser.hasNewMessage = true;//群发
            }
        }

    }

    //点击某个用户 或者 群发，分成 私聊和公聊
    setReceiver(res: any) {
        this.receiver = res;
        //this.toID = this.receiver.userID;
        let toUserName = this.receiver.userName;

        if (toUserName != 'all') { //私信用户
            if (!this.privateMessages[toUserName]) {
                this.privateMessages[toUserName] = [];

                //使用 LS 处理
                this.privateMessages[toUserName]
                    = this.getPrivateMessagesFromLS(this.loginInfo.userName, this.receiver.userName);
            }
            else {
                //群聊信息不用初始化,不用再读取 LS
                //this.privateMessages[toUserName] = [];
            }

            this.messages = this.privateMessages[toUserName];

        } else {//广播
            this.messages = this.publicMessages;
        }

        //找到该用户,他的消息标记去掉 未读
        var user = this.userService.get(this.users, toUserName, toUserName);
        if (user) {
            user.hasNewMessage = false;
        }
        else {
            //do nothing
        }
    }

    //消息读写 LS 处理的公用函数
    setPrivateMessagesToLS(from, to, value) {
        var item = "message_" + from + "_with_" + to;
        this.localStorageService.set(item, value);
    };

    getPrivateMessagesFromLS(from, to) {
        var result = [];
        var item = "message_" + from + "_with_" + to;
        var value = this.localStorageService.get(item);
        var x: any;
        x = value;
        if (x instanceof Array) {
            for (var i = 0; i < x.length; i++) {
                result.push(x[i]);
            }
        }

        return result;
    };

    setPublicMessagesToLS(value) {
        console.log('setPublicMessagesToLS---');
        var item = "message_all";
        this.localStorageService.set(item, value);
    };

    getPublicMessagesFromLS() {
        var result = [];
        var item = "message_all";
        var value = this.localStorageService.get(item);
        var x: any;
        x = value;

        if (x instanceof Array) {
            for (var i = 0; i < x.length; i++)
                result.push(x[i]);
        }

        return result;
    };

}
